package tau.dimes.web;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tau.dimes.beans.LoginBean;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

	private String contextPath;
    private String loginPage;
    private Pattern ignorePattern;
    private Pattern redirectPattern;

	/**
     * Default constructor. 
     */
    public LoginFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest httpRequest = (HttpServletRequest)request;
    	HttpServletResponse httpResponse = (HttpServletResponse)response;

    	String relativeURI = httpRequest.getRequestURI();
    	if (relativeURI.startsWith(contextPath))
    		relativeURI = relativeURI.substring(contextPath.length());
    	
    	if (!ignorePattern.matcher(relativeURI).matches() && !httpRequest.getRequestURI().contains(this.loginPage))
    	{
	    	LoginBean login = (LoginBean)httpRequest.getSession().getAttribute("login");
	    	if (login == null || !login.isLoggedIn())
	    	{
	    		if (httpRequest.getMethod().equalsIgnoreCase("GET") && redirectPattern.matcher(relativeURI).matches())
	    		{
	    			String redirectUrl = httpRequest.getContextPath() + this.loginPage;
	    			redirectUrl += "?returnUrl=" + httpRequest.getRequestURI();
	    			httpResponse.sendRedirect(redirectUrl);
	    		}
	    		else
	    			httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
	    		return;
	    	}
    	}

   		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.contextPath = fConfig.getServletContext().getContextPath();
		this.loginPage = fConfig.getInitParameter("LoginPage");
		this.ignorePattern = Pattern.compile(fConfig.getInitParameter("IgnoreRegexp"));
		this.redirectPattern = Pattern.compile(fConfig.getInitParameter("RedirectRegexp"));
	}
}
